package com.iotboss.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.iotboss.common.constant.WeChatConstant;
import com.iotboss.common.properties.WeChatProperties;
import com.iotboss.common.utils.http.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;

@Component
@Slf4j
public class WechatLoginUtils {

    @Autowired
    WeChatProperties weChatProperties;
    /**
     * 获取accesstoken
     *
     * @return
     */
    private String getAccessToken() throws IOException {
        String apiUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + weChatProperties.getAppid() + "&secret=" + weChatProperties.getSecret();

        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpGet httpGet = new HttpGet(apiUrl);
        HttpResponse response = httpClient.execute(httpGet);
        String responseBody = EntityUtils.toString(response.getEntity());

// 解析返回的JSON数据，获取access_token
        JSONObject jsonObject = new JSONObject(responseBody.isEmpty());
        String accessToken = jsonObject.getString("access_token");
        return accessToken;
    }

    /**
     * 获取手机号
     */
    public String getPhoneNumber(String code) throws IOException {

        String phoneNumber = "";
        String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + getAccessToken();
        HashMap<String, String> params = new HashMap<>();
        params.put("code", code);
        try {
            String resultString = HttpClientUtil.doPost(url, params);
            log.info("获取微信手机号码：{}", resultString);
            if (StringUtils.isNotEmpty(resultString)) {
                JSONObject jsonObject = JSON.parseObject(resultString);
                JSONObject phone_info = jsonObject.getJSONObject(WeChatConstant.WX_PHONE_INFO);
                phoneNumber = phone_info.getString(WeChatConstant.WX_PHONE_NUMBER);
            } else {
                log.error("返回值为空，请检查请求报文或者请求地址是否正确");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return phoneNumber;
    }
}
